package com.backend.server.service.impl;

import com.backend.server.service.LicenseInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.server.common.ErrorCode;
import com.common.server.constant.LicenseConstant;
import com.common.server.entity.license.LicenseInfo;
import com.common.server.entity.license.dto.LicenseInfoQueryRequest;
import com.common.server.entity.license.vo.LicenseInfoVO;
import com.common.server.enums.LicenseStatusEnum;
import com.common.server.exception.BusinessException;
import com.common.server.exception.ThrowUtils;
import com.common.server.mapper.LicenseInfoMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author Lenovo
 * @description 针对表【license_info(许可证信息)】的数据库操作Service实现
 * @createDate 2024-12-25 13:40:29
 */
@Service
public class LicenseInfoServiceImpl extends ServiceImpl<LicenseInfoMapper, LicenseInfo>
        implements LicenseInfoService {

    @Override
    public Page<LicenseInfoVO> getLicenseInfoPage(LicenseInfoQueryRequest request) {
        long current = request.getCurrent();
        long size = request.getSize();
        // 非空
        ThrowUtils.throwIf(current < 0 || size < 0, ErrorCode.PARAMS_ERROR, "分页条件有误");
        // 分页查询
        Page<LicenseInfo> licenseInfoPage = this.page(new Page<>(current, size),
                getQueryWrapper(request));
        // 转换
        List<LicenseInfo> licenseInfoList = licenseInfoPage.getRecords();
        List<LicenseInfoVO> licenseInfoVOList = this.getLicenseInfoVO(licenseInfoList);
        // 返回
        Page<LicenseInfoVO> licenseInfoVOPage = new Page<>();
        BeanUtils.copyProperties(licenseInfoPage, licenseInfoVOPage);
        licenseInfoVOPage.setRecords(licenseInfoVOList);
        licenseInfoVOPage.setTotal(licenseInfoList.size());
        return licenseInfoVOPage;
    }

    private List<LicenseInfoVO> getLicenseInfoVO(List<LicenseInfo> licenseInfoList) {
        Gson gson = new Gson();
        // 转换
        return licenseInfoList.stream().map(licenseInfo -> {
            LicenseInfoVO licenseInfoVO = new LicenseInfoVO();
            BeanUtils.copyProperties(licenseInfo, licenseInfoVO);
            // 确保类型安全
            Type listType = new TypeToken<List<String>>() {
            }.getType();
            // 解析JSON字符串
            licenseInfoVO.setIpAddress(gson.fromJson(licenseInfo.getIpAddress(), listType));
            licenseInfoVO.setMacAddress(gson.fromJson(licenseInfo.getMacAddress(), listType));
            return licenseInfoVO;
        }).collect(Collectors.toList());
    }

    public QueryWrapper<LicenseInfo> getQueryWrapper(LicenseInfoQueryRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "获取证书列表所需参数不能为空");
        }
        String id = request.getId();
        String licenseName = request.getLicenseName();
        Long projectId = request.getProjectId();
        Integer validityDays = request.getValidityDays();
        String applicantName = request.getApplicantName();
        Integer status = request.getStatus();
        QueryWrapper<LicenseInfo> queryWrapper = new QueryWrapper<>();
        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(projectId), "project_id", projectId);
        queryWrapper.like(StringUtils.isNotEmpty(licenseName) && licenseName.length() <= LicenseConstant.LICENSE_NAME, "license_name", licenseName);
        queryWrapper.like(StringUtils.isNotEmpty(applicantName) && applicantName.length() <= LicenseConstant.APPLICANT_NAME, "applicant_name", applicantName);
        queryWrapper.eq(!ObjectUtils.isEmpty(validityDays) && validityDays >= LicenseConstant.VALIDITY_DAYS_MIN && validityDays <= LicenseConstant.VALIDITY_DAYS_MAX, "validity_days", validityDays);
        queryWrapper.eq(!ObjectUtils.isEmpty(status) && !ObjectUtils.isEmpty(LicenseStatusEnum.getEnumByValue(status)), "status", status);
        // 默认排序
        String sortField = request.getSortField();
        Boolean sortOrder = request.getSortOrder();
        // 如果用户没有提供有效的排序字段，则使用默认值
        if (StringUtils.isBlank(sortField)) sortField = LicenseConstant.DEFAULT_SORT_FIELD;
        // 如果用户没有提供有效的排序方式，则使用默认值
        if (sortOrder == null) sortOrder = LicenseConstant.DEFAULT_SORT_ORDER;
        queryWrapper.orderBy(StringUtils.isNotEmpty(sortField), sortOrder, sortField);
        return queryWrapper;
    }
}




